package cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import cn.dao.provider.ProviderMapper;
import cn.dao.user.UserMapper;
import cn.pojo.Provider;
import cn.pojo.User;
import cn.util.MyBatisUtil;


/**
 * Servlet implementation class MainServlet
 */
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(MainServlet.class);   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String path=request.getServletPath();
		path=path.substring(1,path.length()-3);
		try {
			if(path.equals("service")||path.equals("doGet")||path.equals("doPost")) {
				response.sendError(500, "禁止访问此地址");
				return;
			}
			Method m=this.getClass().getDeclaredMethod(path, HttpServletRequest.class,HttpServletResponse.class);
			m.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			response.sendError(500,"地址["+path+"]不存在");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			this.doGet(request, response);
	}
	
	//登录
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("登录===========>");
		String name=request.getParameter("username");
		name=new String(name.getBytes("ISO-8859-1"),"utf-8");
		String password=request.getParameter("password");
		response.setCharacterEncoding("GBK");
		PrintWriter out=response.getWriter();
		SqlSession sqlSession=null;
		try {
			sqlSession=MyBatisUtil.createSqlSession();
			User user=sqlSession.getMapper(UserMapper.class).login(name, password);
			sqlSession.commit();
			if(user!=null) {
				request.getSession().setAttribute("loginName", name);
				request.getRequestDispatcher("welcome.html").forward(request, response);
			}else {
				out.print("<script>alert('用户名或密码错误！');history.back();</script>");
			}
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		}finally {
			MyBatisUtil.closeSqlSession(sqlSession);
		}		
	}
	
	//查询所有供应商
	protected void findAllProvider(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("查询所有供应商===========>");
		SqlSession sqlSession=null;
		try {
			sqlSession=MyBatisUtil.createSqlSession();
			List<Provider> providerList=sqlSession.getMapper(ProviderMapper.class).findAllProvider();
			sqlSession.commit();
			request.getSession().setAttribute("providerList", providerList);
			request.getRequestDispatcher("providerList.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		}finally {
			MyBatisUtil.closeSqlSession(sqlSession);
		}		
	}
	
	//添加供应商
	protected void addProvider(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("添加所有供应商===========>");
		String proCode=request.getParameter("providerId");
		String proName=request.getParameter("providerName");
		String proContact=request.getParameter("people");
		String proPhone=request.getParameter("phone");
		String proAddress=request.getParameter("address");
		String proFax=request.getParameter("fax");
		String proDesc=request.getParameter("describe");
		Provider provider=new Provider(proCode, proName, proDesc, proContact, proPhone, proAddress, proFax);
		SqlSession sqlSession=null;
		response.setCharacterEncoding("GBK");
		PrintWriter out=response.getWriter();
		try {
			sqlSession=MyBatisUtil.createSqlSession();
			int line=sqlSession.getMapper(ProviderMapper.class).addProvider(provider);
			sqlSession.commit();
			if(line>0) {
				response.sendRedirect("findAllProvider.do");
			}else {
				out.print("<script>alert('新增失败！');history.back();</script>");
			}
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		}finally {
			MyBatisUtil.closeSqlSession(sqlSession);
		}
	}
}
